<?php

namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\AdminRegLog;
use app\common\entity\Mywallet;
use app\common\entity\MywalletLog;
use app\common\entity\PosLog;
use app\common\entity\Proportion;
use app\common\entity\RechargeList;
use app\common\entity\User;
use app\common\entity\Currency;
use app\common\entity\UserPackage;
use app\common\shop\WithdrawLogModel;
use app\index\model\SendCode;
use think\Db;
use think\Model;
use think\Request;
use app\common\entity\Task;
use PHPExcel_IOFactory;
use PHPExcel;
use think\facade\Env;
use app\common\entity\AccountPos;

class Wallet extends Admin
{
    /**
     * [提现]
     * @param
     * @return
     */
    public function withdrawal( Request $request ){
        $map = [];
        $w = WithdrawLogModel::alias('w')->field('w.*,u.mobile,u.nick_name,u.wx,u.wx_name,u.zfb,u.zfb_name');
        if($type = input('type')){
            if($type == 'nick_name'){
                $w->where('u.nick_name','like','%'.input('keyword').'%');
            }elseif($type == 'mobile'){
                $w->where('u.mobile','like','%'.input('keyword').'%');
            }elseif($type == 'id'){
                $w->where('u.id',input('keyword'));
            }
            $map['keyword'] = input('keyword');
        }

        $list = $w
            ->leftJoin('user u','u.id=w.uid')
            ->order('w.createtime desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        return $this->render('withdrawal', [
            'list' => $list
        ]);
    }
    /**
     * [审核提现]
     * @param
     * @return
     */
    public function checkwithdrawal( Request $request ){
        $input = input();

        $info = WithdrawLogModel::where('id',$input['id'])->find();
        if(empty($info)) return json()->data(['code'=>1,'message'=>'信息错误']);
        if($info['status'] != 0 ) return json()->data(['code'=>1,'message'=>'已审核']);
        if($input['status'] == 2){
            // 拒绝-返还提现金额
            MywalletLog::addLog($info['uid'], $info['money'], 4, '提现失败', '6', 1);
        }
        WithdrawLogModel::where('id',$input['id'])->update(['status'=>$input['status'],'finishtime'=>time()]);
        return json(['code' => 0, 'toUrl' => url('/admin/wallet/withdrawal')]);
    }
    /**
     * @power 钱包管理|币种管理
     */
    public function index(Request $request)
    {

        $list = Currency::select();

        return $this->render('index', [
            'list' => $list
        ]);
    }


    /**
     * 添加币种
     */
    public function setadd(Request $request)
    {
        $config = new Currency();
        $config->title = $request->post('title');
        $config->islegal = $request->post('islegal');
        $config->address = $request->post('address');
        $config->imgs = $request->post('imgs');

        $config->createtime = $request->time();

        $entity = \app\common\entity\Currency::where('title', $config->title)->find();
        if ($entity) {
            throw new AdminException('币种已存在');
        }

        if ($config->save() === false) {
            throw new AdminException('添加失败');
        }
        return ['code' => 0, 'message' => '添加成功，2秒后自动跳转'];
    }

    /**
     * 添加修改币种
     */
    public function edit(Request $request)
    {

        $entity = $this->checkInfo($request->post('id'));

        $entity1 = \app\common\entity\Currency::where('title', $request->post('title'))->where('id', '<>', $request->post('id'))->find();
        // print_r($entity1);
        if ($entity1) {
            throw new AdminException('币种已存在');
        }

        $service = new \app\common\entity\Currency();

        $result = $service->editCurrency($entity, $request->post());

        if ($result === false) {
            throw new AdminException('修改失败');
        }

        return ['code' => 0, 'message' => '修改成功，2秒后自动跳转'];
    }

    private function checkInfo($id)
    {
        $entity = \app\common\entity\Currency::where('id', $id)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }


        return $entity;
    }


    #行情比例列表
    public function ratiolist(Request $request)
    {
        $list = Db::table('proportion')->order('date desc')->select();
        return $this->render('ratiolist', [
            'list' => $list
        ]);
    }

    #行情比例添加
    public function ratioadd(Request $request)
    {
        $validate = $this->validate($request->post(), 'app\admin\validate\Ratio');

        if ($validate !== true) {
            return json(['code' => 1, 'message' => $validate]);
        }
        $date = $request->post('date');
        $ratio = $request->post('ratio');
        $data = [
            'date' => $date,
            'ratio' => $ratio,
            'create_time' => time()
        ];
        $res = Db::table('proportion')->insert($data);
        if ($res) {
            return json(['code' => 0, 'message' => '添加成功']);
        }
        return json(['code' => 1, 'message' => '添加失败']);

    }


    #行情比例更新
    public function ratioupd(Request $request)
    {
        // $validate = $this->validate($request->post(), 'app\admin\validate\Ratio');

        // if ($validate !== true) {
        //     return json(['code' => 1, 'message' => $validate]);
        // }
        $date = $request->post('date');
        $ratio = $request->post('ratio');
        $id = $request->post('id');
        $today_ratio = $request->post('today_ratio');
        $data = [
            'date' => $date,
            'ratio' => $ratio,
            'create_time' => time(),
            'today_ratio'=>$today_ratio
        ];
        $res = Db::table('proportion')->where('id', $id)->update($data);
        if ($res) {
            return json(['code' => 0, 'message' => '修改成功']);
        }
        return json(['code' => 1, 'message' => '修改失败']);

    }

    #删除行情比例
    public function del_ratio(Request $request)
    {

        $id = $request->post('id');

        $count = Db::table('proportion')->count('id', $id);
        if($count <=1){
            return json(['code' => 1, 'message' => '最后一条了，不要再删了']);
        }

        
        $res = Db::table('proportion')->where('id', $id)->delete();
        if ($res) {
            return json(['code' => 0, 'message' => '删除成功']);
        }
        return json(['code' => 1, 'message' => '删除失败']);

    }



    #财务记录
    public function walletLogList(Request $request)
    {
        $entity = MywalletLog::alias('um')->field('um.*,u.mobile,u.nick_name,u.level');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($money_type = $request->get('money_type')) {
            $entity->where('um.money_type', $money_type);
            $map['money_type'] = $money_type;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->order('um.id', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        $count = '0';

        return $this->render('walletLogList', [
            'user' => new User(),
            'logmodel' => new MywalletLog(),
            'list' => $list,
            'count' => $count,
        ]);
    }

    //取消屏蔽
    public function show_yes($id)
    {
        $res = \app\common\entity\OtcMatch::where('id', $id)->update(['is_show' => 0]);

        if (!$res) {
            throw new AdminException('禁用失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    //屏蔽
    public function show_no($id)
    {
        $res = \app\common\entity\OtcMatch::where('id', $id)->update(['is_show' => 1]);

        if (!$res) {
            throw new AdminException('禁用失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    #交易状态记录
    public function marketList(Request $request)
    {
        $entity = \app\common\entity\OtcMatch::alias('um')->field('um.*,u.nick_name,u.mobile,uu.nick_name as from_nick_name,uu.mobile as from_mobile');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($keyword1 = $request->get('keyword1')) {
            $entity->where('uu.mobile', $keyword1);
            $map['keyword1'] = $keyword1;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.status', $types);
            $map['types'] = $types;
        }

        if ($types = $request->get('types')) {
            $entity->where('um.trade_type', $types);
            $map['m_types'] = $types;
        }
        if ($time_types = $request->get('time_types')) {
            $map['time_types'] = $time_types;
            $startTime = $request->get('startTime');
            $endTime = $request->get('endTime');
            if($startTime){
                $map['startTime'] = $startTime;
                $entity->where('um.'.$time_types, '>=',strtotime($startTime));
            }
            if($endTime){
                $map['endTime'] = $endTime;
                $entity->where('um.'.$time_types, '<=',strtotime($endTime));
            }

        }


        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.from_id = u.id')
            ->leftJoin('user uu', 'um.uid = uu.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        
        $count = '0';
        //print_r(json_decode(json_encode($list),true));die;
        return $this->render('marketList', [
            'list' => $list,
            'count' => $count,
        ]);
    }


    #提币记录
    public function rechargeList(Request $request)
    {
        $entity = Db::name('withdraw_money')->alias('um')->field('um.*,u.nick_name');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }

        if ($types = $request->get('types')) {
            $entity->where('um.status', $types);
            $map['types'] = $types;
        }


        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        $count = '0';

        return $this->render('rechargeList', [
            'list' => $list,
            'count' => $count,
        ]);
    }


    #提币拒绝
    public function reg_no(Request $request)
    {
        $id = $request->get('id');

        $info = Db::name('withdraw_money')->where('id', $id)->find();
        $upd = Db::name('withdraw_money')->where('id', $id)->update(['status' => 3, 'update_time' => time()]);


        if ($upd) {
            MywalletLog::addLog($info['user_id'], $info['num'], 1, '拒绝提币', 8, 1);
            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }


    #提币同意
    public function reg_yes(Request $request)
    {
        $id = $request->get('id');
        $upd =  Db::name('withdraw_money')->where('id', $id)->update(['status' => 2, 'update_time' => time()]);
        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }

    #撤销所有
    public function killall()
    {
        $del_market = \app\common\entity\OtcMatch::where('status', 1)->update(['status' => 6]);
        if ($del_market) {
            return json(['code' => 0, 'message' => '撤销成功']);
        }
        return json(['code' => 1, 'message' => '撤销失败']);
    }



    public function task(){
        return $this->render('task', [
            'list' => Task::order('water id')->select(),
        ]);
    }
    public function updateTask(Request $request){

        if($id = $request->get('id')){
            $info = Task::where('id',$id)->find();
            return $this->render('taskedit', [
                'info' => $info,
            ]);
        }else{
            return $this->render('taskedit', [
            ]);
        }

    }
    public function saveTask(Request $request){
        $model = new Task();
        if($id = $request->get('id')){
            $data = $request->post();
            $data['update_time'] = time();
            $update = $model->where('id',$id)->update($data);
        }else{
            $update = $model->save($request->post());
        }

        if($update) {
            return json(['code' => 0, 'message' => '更新成功','toUrl'=>url('task')]);
        }else{
            return json(['code' => 1, 'message' => '更新失败']);
        }

    }
    public function delTask(Request $request){
        if($id = $request->get('id')){
            $delete = Task::where('id',$id)->delete();
            if($delete) {
                return json(['code' => 0, 'message' => '更新成功','toUrl'=>url('task')]);
            }else{
                return json(['code' => 1, 'message' => '更新失败']);
            }
        }
    }



    public function searchNameAttr($query, $value, $data)
    {
        $query->where('name','like', $value . '%');
    }





    #后台充值记录
    public function adminRegList(Request $request)
    {
        $entity = AdminRegLog::alias('um')->field('um.*,u.mobile,u.level');
        if ($money_type = $request->get('money_type')) {
            $entity->where('um.money_type', $money_type);
            $map['money_type'] = $money_type;
        }
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'nick_name':
                    $entity->where('u.mobile', $keyword);
                    break;

            }
            $map['type'] = $type;

            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        return $this->render('adminRegList', [
            'lists' => $list,
            'logModel'=>new MywalletLog(),
        ]);
    }



    public function posLog(Request $request){
        $entity = PosLog::alias('p')->join('user u','u.pos = p.sn_id')->field('p.*,u.mobile');

        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'sn_id':
                    $entity->where('p.sn_id', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }

        $startTime = $request->get('startTime');
        $endTime = $request->get('endTime');
        if($startTime){
            $map['startTime'] = $startTime;
            $entity->where('p.create_time', '>=',strtotime($startTime));
        }
        if($endTime){
            $map['endTime'] = $endTime;
            $entity->where('p.create_time', '<=',strtotime($endTime));
        }






        $list = $entity->order('create_time desc')->paginate(15, false, [
            'query' => isset($map) ? $map : []
            ]);
        echo $entity->getLastSql();
        return $this->render('posLog', [
            'list' => $list,
        ]);
    }
}
